<template>
    <div class="post-detail">
        <el-card class="box-card" v-loading="loading">
            <template #header>
                <div class="card-header">
                    <span>帖子详情</span>
                    <el-button @click="goBack" type="text">返回列表</el-button>
                </div>
            </template>

            <div v-if="post" class="post-content-wrapper">
                <!-- 帖子标题和分类 -->
                <div class="post-title-area">
                    <h1 class="post-title">{{ post.title }}</h1>
                    <el-tag v-if="post.category" size="small">{{ getCategoryLabel(post.category) }}</el-tag>
                </div>

                <!-- 作者信息和发布时间 -->
                <div class="post-meta">
                    <div class="author-info">
                        <el-avatar :size="40" :src="post.avatar || defaultAvatar"></el-avatar>
                        <span class="author-name">{{ post.username || post.nickname || '未知用户' }}</span>
                    </div>
                    <div class="post-time">
                        <span>发布于：{{ formatTime(post.createdAt) }}</span>
                    </div>
                </div>

                <!-- 帖子内容 -->
                <div class="post-content">
                    {{ post.content }}
                </div>

                <!-- 帖子统计信息 -->
                <div class="post-stats">
                    <span><el-icon><View /></el-icon> 浏览 {{ post.viewCount || 0 }}</span>
                    <span class="comment-count" @click="scrollToComments">
                        <el-icon><ChatDotRound /></el-icon> 评论 {{ post.commentCount || 0 }}
                    </span>
                    <span class="like-container">
                        <el-icon 
                            class="like-icon" 
                            :class="{ 'like-active': isLikeAnimating }"
                            @click="throttledLikePost"
                        >
                            <StarFilled />
                        </el-icon>
                        <span>点赞 {{ post.likeCount || 0 }}</span>
                    </span>
                </div>

                <!-- 评论区 -->
                <div class="comments-section">
                    <h3>评论区 ({{ post.commentCount || 0 }})</h3>
                    
                    <!-- 添加评论 -->
                    <div class="comment-form" v-if="isLoggedIn" v-loading="userProfileLoading">
                        <div class="form-header">
                            <el-avatar :size="40" :src="currentUser.avatar || defaultAvatar"></el-avatar>
                            <div class="user-info">
                                <span class="username">
                                    {{ currentUser.nickname || currentUser.username || '您' }}
                                    <el-tooltip v-if="userProfile" content="个人资料已同步" placement="top">
                                        <el-icon class="sync-icon"><Check /></el-icon>
                                    </el-tooltip>
                                    <el-tooltip v-if="userProfileError" content="获取个人资料失败，使用本地缓存" placement="top">
                                        <el-icon class="error-icon"><Warning /></el-icon>
                                    </el-tooltip>
                                </span>
                                <span class="subtitle" v-if="userProfileLoading">正在同步您的个人资料...</span>
                                <span class="subtitle error" v-else-if="userProfileError">获取个人资料失败，使用本地缓存</span>
                            </div>
                        </div>
                        <el-input
                            v-model="newComment"
                            type="textarea"
                            :rows="3"
                            placeholder="写下您的评论..."
                            maxlength="500"
                            show-word-limit
                            ref="commentInputRef"
                            @keydown.ctrl.enter="submitComment"
                        ></el-input>
                        <div class="form-actions">
                            <span class="keyboard-tip">提示: 按下 Ctrl + Enter 快速发送</span>
                            <el-button type="primary" @click="submitComment" :loading="commentSubmitting">发表评论</el-button>
                        </div>
                    </div>
                    <el-alert
                        v-else
                        title="请先登录后再发表评论"
                        type="info"
                        :closable="false"
                        show-icon
                    />

                    <!-- 评论列表 -->
                    <div v-loading="commentsLoading" element-loading-text="评论加载中...">
                        <div class="comments-list" v-if="comments.length > 0">
                            <div class="comment-item" v-for="comment in comments" :key="comment.id">
                                <div class="comment-header">
                                    <div class="comment-user">
                                        <el-avatar :size="40" :src="getCommentAuthorAvatar(comment)" class="comment-avatar"></el-avatar>
                                        <div class="user-info">
                                            <div class="username">{{ getCommentAuthorName(comment) }}</div>
                                            <div class="comment-time">{{ formatTime(comment.createdAt) }}</div>
                                        </div>
                                    </div>
                                    <el-button 
                                        v-if="isCurrentUserComment(comment)" 
                                        @click="deleteUserComment(comment.id)" 
                                        type="danger" 
                                        size="small" 
                                        text
                                    >删除</el-button>
                                </div>
                                <div class="comment-content">{{ comment.content }}</div>
                            </div>
                            
                            <!-- 分页器 -->
                            <div class="comments-pagination" v-if="totalComments > commentsPerPage">
                                <el-pagination
                                    v-model:current-page="currentPage"
                                    :page-size="commentsPerPage"
                                    layout="prev, pager, next"
                                    :total="totalComments"
                                    @current-change="handlePageChange"
                                    background
                                />
                            </div>
                        </div>
                        <el-empty v-else description="暂无评论，来抢沙发吧~" />
                    </div>
                </div>
            </div>

            <el-empty v-else-if="!loading" description="帖子不存在或已被删除" />
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { View, ChatDotRound, StarFilled, Check, Warning } from "@element-plus/icons-vue";
import postsApi, { type Post } from '@/api/posts';
import commentsApi, { type Comment } from '@/api/comments';
import userApi, { type UserProfile } from '@/api/user';
import { useApartmentUserStore } from '@/store/modules/apartmentUser';

const router = useRouter();
const route = useRoute();
const loading = ref(false);
const post = ref<Post | null>(null);
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png';
const userProfile = ref<UserProfile | null>(null);
const userProfileLoading = ref(false);
const userProfileError = ref(false);
const isLikeAnimating = ref(false);
const canLike = ref(true); // 用于节流控制
const comments = ref<Comment[]>([]);
const currentPage = ref(1);
const commentsPerPage = 10;
const totalComments = ref(0);
const newComment = ref('');
const commentSubmitting = ref(false);
const commentsLoading = ref(false);
const apartmentUserStore = useApartmentUserStore();
const commentInputRef = ref<any>(null);

// 分类选项
const categories = [
    { value: 'apartment', label: '公寓信息' },
    { value: 'roommate', label: '室友寻找' },
    { value: 'experience', label: '居住体验' },
    { value: 'question', label: '问题咨询' },
    { value: 'other', label: '其他' },
];

// 获取分类标签
const getCategoryLabel = (categoryValue: string): string => {
    const category = categories.find(c => c.value === categoryValue);
    return category ? category.label : '其他';
};

// 格式化时间
const formatTime = (time: Date | string | undefined): string => {
    if (!time) return '';
    
    const date = new Date(time);
    
    // Format: YYYY-MM-DD HH:MM:SS
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 获取帖子详情
const fetchPostDetail = async (postId: string) => {
    loading.value = true;
    try {
        const data = await postsApi.getPost(postId);
        post.value = data;
        console.log('Fetched post details:', data);
    } catch (error) {
        console.error('Error fetching post details:', error);
        ElMessage.error('获取帖子详情失败');
        post.value = null;
    } finally {
        loading.value = false;
    }
};

// 返回列表
const goBack = () => {
    router.push('/posts/main');
};

// 点赞帖子（添加节流功能）
const likeCurrentPost = async () => {
    if (!canLike.value) return;
    
    if (!post.value || !post.value.id) {
        ElMessage.error('帖子不存在');
        return;
    }
    
    // 设置节流，1秒内不能再次点赞
    canLike.value = false;
    setTimeout(() => {
        canLike.value = true;
    }, 1000);
    
    // 设置动画效果
    isLikeAnimating.value = true;
    setTimeout(() => {
        isLikeAnimating.value = false;
    }, 500);
    
    try {
        const updatedPost = await postsApi.likePost(post.value.id);
        post.value = updatedPost;
        ElMessage.success('点赞成功！');
    } catch (error) {
        console.error('点赞失败:', error);
        ElMessage.error('点赞失败，请稍后再试');
    }
};

// 使用节流的点赞函数
const throttledLikePost = () => {
    if (canLike.value) {
        likeCurrentPost();
    }
};

// 检查用户是否登录
const isLoggedIn = computed(() => {
    return !!apartmentUserStore.userId && apartmentUserStore.userId !== '';
});

// 获取当前用户信息 - 使用数据库中的最新数据
const fetchCurrentUserProfile = async () => {
    if (!isLoggedIn.value) return;
    
    userProfileLoading.value = true;
    userProfileError.value = false;
    
    try {
        const profile = await userApi.getCurrentUserProfile();
        userProfile.value = profile;
        
        // 确保 profile 是一个有效对象
        if (profile && typeof profile === 'object') {
            // 更新 Pinia store 中的用户信息，保持一致性
            apartmentUserStore.setUserInfo({
                userId: profile.id,
                username: profile.name || '',
                nickname: profile.nickname || '',
                avatar: profile.avatarUrl || ''
            });
        }
        
        console.log('Fetched user profile:', profile);
    } catch (error) {
        console.error('Error fetching user profile:', error);
        userProfileError.value = true;
        ElMessage.warning({
            message: '获取用户资料失败，将使用本地缓存的信息',
            duration: 3000
        });
    } finally {
        userProfileLoading.value = false;
    }
};

// 获取当前用户信息
const currentUser = computed(() => {
    // 如果已从数据库获取到最新的用户资料，优先使用它
    if (userProfile.value) {
        return {
            id: userProfile.value.id,
            username: userProfile.value.name || '',  // 使用 name 字段
            nickname: userProfile.value.nickname || '',
            avatar: userProfile.value.avatarUrl || '' // 使用 avatarUrl 字段
        };
    }
    
    // 否则回退到 Pinia store 中的信息
    return {
        id: apartmentUserStore.userId,
        username: apartmentUserStore.username,
        nickname: apartmentUserStore.nickname,
        avatar: apartmentUserStore.avatar
    };
});

// 检查评论是否由当前用户发表
const isCurrentUserComment = (comment: Comment): boolean => {
    return comment.authorId === currentUser.value.id;
};

// 处理分页变化
const handlePageChange = (page: number) => {
    currentPage.value = page;
    if (post.value && post.value.id) {
        fetchComments(post.value.id);
    }
};

// 获取评论列表
const fetchComments = async (postId: string) => {
    commentsLoading.value = true;
    try {
        const data = await commentsApi.getCommentsByPost(postId, {
            page: currentPage.value,
            limit: commentsPerPage
        });
        comments.value = data;
        
        // 获取总评论数
        totalComments.value = post.value?.commentCount || 0;
        
        console.log('Fetched comments:', data);
    } catch (error) {
        console.error('Error fetching comments:', error);
        ElMessage.error('获取评论失败');
    } finally {
        commentsLoading.value = false;
    }
};

// 提交评论
const submitComment = async () => {
    if (!newComment.value.trim()) {
        ElMessage.warning('评论内容不能为空');
        return;
    }

    if (!post.value || !post.value.id) {
        ElMessage.error('帖子不存在');
        return;
    }

    if (!isLoggedIn.value) {
        ElMessage.warning('请先登录后再发表评论');
        return;
    }

    commentSubmitting.value = true;
    try {
        await commentsApi.createComment({
            content: newComment.value,
            authorId: currentUser.value.id,
            postId: post.value.id
        });
        
        // 清空输入框
        newComment.value = '';
        
        // 刷新帖子信息以更新评论数量
        await fetchPostDetail(post.value.id);
        
        // 重置到第一页并刷新评论列表，确保新评论显示在最前面
        currentPage.value = 1;
        await fetchComments(post.value.id);
        
        ElMessage.success('评论发表成功');
    } catch (error) {
        console.error('Error submitting comment:', error);
        ElMessage.error('评论发表失败，请稍后再试');
    } finally {
        commentSubmitting.value = false;
    }
};

// 删除评论
const deleteUserComment = async (commentId: string) => {
    try {
        // 添加确认对话框
        await ElMessageBox.confirm(
            '确定要删除这条评论吗？',
            '删除确认',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        );
        
        if (!post.value || !post.value.id) {
            ElMessage.error('帖子不存在');
            return;
        }
        
        await commentsApi.deleteComment(commentId, currentUser.value.id);
        
        // 刷新帖子信息以更新评论数量
        await fetchPostDetail(post.value.id);
        
        // 刷新评论列表
        await fetchComments(post.value.id);
        
        ElMessage.success('评论已删除');
    } catch (error) {
        // 如果是用户取消，不显示错误信息
        if (error !== 'cancel' && error.toString() !== 'Error: cancel') {
            console.error('Error deleting comment:', error);
            ElMessage.error('删除评论失败，请稍后再试');
        }
    }
};

// 滚动到评论区并聚焦到评论框
const scrollToComments = () => {
    document.querySelector('.comments-section')?.scrollIntoView({ 
        behavior: 'smooth',
        block: 'start'
    });
    
    // 延迟聚焦，确保滚动完成
    setTimeout(() => {
        commentInputRef.value?.input?.focus();
    }, 500);
};

// 获取评论作者的头像
const getCommentAuthorAvatar = (comment: Comment): string => {
    return comment.author?.avatarUrl || comment.author?.avatar || defaultAvatar;
};

// 获取评论作者的名称
const getCommentAuthorName = (comment: Comment): string => {
    return comment.author?.nickname || comment.author?.name || comment.author?.username || '未知用户';
};

onMounted(() => {
    // 从查询参数中获取帖子ID
    const postId = route.query.pid as string;
    if (postId) {
        console.log('Fetching post with ID:', postId);
        fetchPostDetail(postId);
        fetchComments(postId);
        fetchCurrentUserProfile(); // 获取最新的用户资料
    } else {
        ElMessage.error('帖子ID不存在');
        router.push('/posts/main');
    }
});
</script>

<style scoped>
.post-detail {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.post-content-wrapper {
    padding: 0 10px;
}

.post-title-area {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    gap: 15px;
}

.post-title {
    font-size: 24px;
    font-weight: bold;
    margin: 0;
}

.post-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25px;
    padding-bottom: 15px;
    border-bottom: 1px solid #ebeef5;
}

.author-info {
    display: flex;
    align-items: center;
    gap: 10px;
}

.author-name {
    font-weight: 500;
}

.post-time {
    color: #909399;
    font-size: 14px;
}

.post-content {
    min-height: 200px;
    font-size: 16px;
    line-height: 1.8;
    word-break: break-word;
    white-space: pre-wrap;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid #ebeef5;
}

.post-stats {
    display: flex;
    gap: 20px;
    margin-bottom: 30px;
    color: #606266;
}

.post-stats span {
    display: flex;
    align-items: center;
    gap: 5px;
}

.like-container {
    display: flex;
    align-items: center;
    gap: 10px;
}

.like-icon {
    cursor: pointer;
    font-size: 18px;
    color: #f56c6c;
    transition: all 0.3s;
}

.like-icon:hover {
    transform: scale(1.2);
}

.like-active {
    animation: like-animation 0.5s;
    color: #f56c6c;
}

@keyframes like-animation {
    0% {
        transform: scale(1);
    }
    50% {
        transform: scale(1.5);
    }
    100% {
        transform: scale(1);
    }
}

.comments-section {
    margin-top: 30px;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
}

.comments-section h3 {
    margin-top: 0;
    margin-bottom: 20px;
    font-weight: 500;
    color: #303133;
    display: flex;
    align-items: center;
}

.comments-section h3::after {
    content: '';
    flex: 1;
    height: 1px;
    background: #ebeef5;
    margin-left: 15px;
}

.comment-form {
    margin-bottom: 30px;
    background-color: #f9f9f9;
    padding: 15px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
}

.comment-form:hover {
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.form-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 10px;
}

.form-header .user-info {
    display: flex;
    flex-direction: column;
}

.form-header .username {
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 5px;
}

.form-header .subtitle {
    font-size: 12px;
    color: #909399;
}

.form-header .subtitle.error {
    color: #f56c6c;
}

.sync-icon {
    color: #67c23a;
    font-size: 14px;
}

.error-icon {
    color: #e6a23c;
    font-size: 14px;
}

.form-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;
}

.keyboard-tip {
    color: #909399;
    font-size: 12px;
}

.comments-list {
    margin-top: 20px;
}

.comment-item {
    padding: 15px;
    margin-bottom: 15px;
    border-bottom: 1px dashed #ebeef5;
    transition: background-color 0.3s ease;
}

.comment-item:hover {
    background-color: #f9f9f9;
}

.comment-item:last-child {
    border-bottom: none;
}

.comment-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.comment-user {
    display: flex;
    align-items: center;
    gap: 10px;
}

.user-info {
    display: flex;
    flex-direction: column;
}

.username {
    font-weight: 500;
    color: #303133;
}

.comment-time {
    font-size: 12px;
    color: #909399;
}

.comment-content {
    padding: 5px 0 5px 50px;
    line-height: 1.6;
    white-space: pre-wrap;
    word-break: break-word;
    color: #303133;
}

.post-stats span.comment-count {
    cursor: pointer;
    transition: color 0.3s;
}

.post-stats span.comment-count:hover {
    color: #409eff;
}

.comments-pagination {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    padding-top: 10px;
}

.comment-avatar {
    border: 2px solid #f0f2f5;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
</style>